<?php
/*
Plugin Name: Fetion Notification Plugin
Plugin URI: http://blog.gotall.net
Description: 飞信通知插件，该插件测试飞信接口，当有人给您留言时，会自动发送留言短信到您的手机。
Version: 0.2
Author: Wyatt Fang
Author URI: http://www.gotall.net
*/

define('FETION_URI', 'http://sms.api.bz/fetion.php');
define('FETION_PLUGIN_PATH', dirname(__FILE__) . '/');

require_once(ABSPATH . 'wp-includes/class-snoopy.php');
require_once(FETION_PLUGIN_PATH . 'validation.class.php');

function fetion_notification_send_message_to_phone($fetion_message) {
	$option_values = fetion_notification_get_option();

    $phone_number = $option_values['fetion_notification_fetion_phone_number'];
    $phone_password = $option_values['fetion_notification_fetion_phone_password'];
    
	$fetion_api_url = FETION_URI . '?username=' . $phone_number . '&password=' . $phone_password . '&sendto=' . $phone_number . '&message=' . $fetion_message;

    $snoopy = new Snoopy();
    $snoopy->fetch($fetion_api_url);
    
    return $snoopy->results;
}

function fetion_notification_new_user_notify($user_id) {
    $user = get_userdata($user_id);
    $user_name = $user->user_login;
    
    $fetion_message = '新用户注册：' . $user_name;
    
    fetion_notification_send_message_to_phone($fetion_message);
}

function fetion_notification_new_comment_notify($comment_array) {
    $fetion_message = $comment_array['comment_author'] . '留言：' . $comment_array['comment_content'];

    fetion_notification_send_message_to_phone($fetion_message);

    return $comment_array;
}

function fetion_notification_send_verify_code($phone_number, $password) {
    $verify_code = rand(1000, 9999);
    setcookie('fetion_notification_verify_code', md5($verify_code), time()+60*60*1);
    
    fetion_notification_send_message_to_phone($phone_number, $password, '您的验证码是：' . $verify_code);
}

function fetion_notification_get_option() {
    $option_name = 'fetion_notification_fetion_configuration';
    $option_value = array (
        'fetion_notification_show_comment_notify' => 0,
        'fetion_notification_fetion_phone_number' => '',
        'fetion_notification_fetion_phone_password' => '',
        'fetion_notification_notification_comment' => 1,
        'fetion_notification_notification_regist' => 1,
    );

    $option_name_values = get_option($option_name);

    if (!empty($option_name_values)) {
        foreach ($option_name_values as $key => $value) {
        	if ('' !== $value && null !== $value) {
                $option_value[$key] = $value;
        	}
        }
    }
    else {
        update_option($option_name, $option_value);
    }

    return $option_value;
}


function fetion_notification_get_setting($setting_name, $echo = true) {
	$fetion_options = fetion_notification_get_option();
	$result = 0;
	
	switch ($setting_name) {
		case 'phone':
			$result = $fetion_options['fetion_notification_fetion_phone_number'];
			
			break;
		case 'password':
			$result =$fetion_options['fetion_notification_fetion_phone_password'];
			break;
		case 'notification-comment':
		    $result = $fetion_options['fetion_notification_notification_comment'];
			
			break;
		case 'notification-regist':
			$result = $fetion_options['fetion_notification_notification_regist'];
	}
	
	if (!$echo) {
		return $result;
	}
	else {
		echo $result;
	}
}

function fetion_notification_show_post_result_message($result) {
    echo '<br /><br />';

    if ('success' == $result) {
        echo '<div class="updated fade" id="message"><p>更新成功！</p></div>';
    }
    else if ('phone_invalide' == $result) {
        echo '<div class="updated fade" id="message"><p>手机号码格式不正确！</p></div>';
    }
    else if ('verify_code_sucess' == $result) {
    	echo '<div class="updated fade" id="message"><p>恭喜，您的手机已经开通了飞信，可以使用！</p></div>';
    }
    else if ('verify_code_failed' == $result) {
    	echo '<div class="updated fade" id="message"><p>抱歉，您输入的验证码错误。如果您还没有开通飞信，请点击这里<a href="http://www.fetion.com.cn/download/" target="_blank">下载飞信客户端</a>，并开通飞信。</p></div>';
    }
}

function fetion_notification_show_verify_ui() {
?>
<form method="post">
<span>请输入您收到手机短信验证码：</span>
<input type="text" name="fetion-notification-verify-code" />
<input type="submit" name="Fetion-Submit-Verify-Code" value="提交验证码" class="button" />
</form>
<?php 
}

function fetion_notification_show_settings_ui() {
?>
<!-- <div class="updated fade" id="message"><p>Settings saved.</p></div> -->
<form method="post">
<h2>飞信短信通知配置</h2>

<h3>飞信帐号设置</h3>
<table class="form-table">
    <tbody><tr valign="top">
        <th scope="row"><label for="fetion-notification-phone-number">手机号码（已开通飞信）</label></th><td><input type="text" value="<?php fetion_notification_get_setting('phone');?>" name="fetion-notification-phone-number" size="100"/> <br/>请确保您输入的手机号已经开通了飞信服务</td></tr>
    <tr valign="top">
        <th scope="row"><label for="fetion-notification-phone-password">飞信密码</label></th><td><input type="password" value="<?php fetion_notification_get_setting('password'); ?>" name="fetion-notification-phone-password" size="100"/> <br/>这里是您的飞信密码的配置<br/></td></tr>
</tbody></table>

<h3>飞信提醒设置</h3>
<table class="form-table">
    <tbody>
      <tr valign="top">
        <th scope="row"><label for="fetion-notification-comment">开启新评论提醒：</label></th>
        <td>
          <input type="checkbox" <?php if (fetion_notification_get_setting('notification-comment', false)) echo '"checked"'?>  name="fetion-notification-comment" /> 
                    开启了新评论提醒，当你收到新的评论或留言时，会发短信提醒您，并将短信内容发送到您的手机。
        </td>
      </tr>
      <tr valign="top">
        <th scope="row"><label for="fetion-notification-regist">开启新用户注册提醒：</label></th>
        <td>
          <input type="checkbox" <?php if (fetion_notification_get_setting('notification-regist', false)) echo '"checked"'?> name="fetion-notification-regist" /> 
                    开启了新用户注册提醒，当有新用户注册时，会发短信提醒您。
        </td>
      </tr>
</tbody></table>

<p class="submit">
    <!-- <input type="submit" value="保存" name="save" class="button"/>-->
    <input type="submit" value="保存" class="button-primary" name="Fetion-Submit"/>
</p>
</form>

<?php
}

function fetion_notification_show_settings() {
    $validation = new Validation();
	if (!empty($_POST['Fetion-Submit'])) {
        //Handle the post request

        $phone_number = $_POST['fetion-notification-phone-number'];
        $phone_password = $_POST['fetion-notification-phone-password'];
        $comment = !empty($_POST['fetion-notification-comment']) ? 1 : 0;
        $regist = !empty($_POST['fetion-notification-regist']) ? 1 : 0;
        //print_r($_POST);
        
        //Validate the phone number
        if ($validation->phone($phone_number)) {
            $option_name = 'fetion_notification_fetion_configuration';
	        $option_value = array (
	            'fetion_notification_show_comment_notify' => 1,
	            'fetion_notification_fetion_phone_number' => $phone_number,
	            'fetion_notification_fetion_phone_password' => $phone_password,
	            'fetion_notification_notification_comment' => $comment,
                'fetion_notification_notification_regist' => $regist,
	        );
	        update_option($option_name, $option_value);
	
	        fetion_notification_show_post_result_message('success');
        }
        else {
        	fetion_notification_show_post_result_message('phone_invalide');
        }
        
        //show the setting form
        fetion_notification_show_settings_ui();
    }
    else if (!empty($_POST['Fetion-Validation'])){
        $phone_number = $_POST['fetion-notification-phone-number'];
        $phone_password = $_POST['fetion-notification-phone-password'];
        if ($validation->phone($phone_number)) {
            fetion_notification_send_verify_code($phone_number, $phone_password);
            fetion_notification_show_settings_ui();
            fetion_notification_show_verify_ui();
        }
        else {
            fetion_notification_show_post_result_message('phone_invalide');
            //show the setting form
            fetion_notification_show_settings_ui();
        }
    }
    else if (!empty($_POST['Fetion-Submit-Verify-Code'])) {
    	$verify_code = md5($_POST['fetion-notification-verify-code']);
    	$verify_code_in_cookie = $_COOKIE['fetion_notification_verify_code'];
    	echo ' ' . $verify_code_in_cookie;
    	
    	if ($verify_code == $verify_code_in_cookie) {
    		fetion_notification_show_post_result_message('verify_code_sucess');
    	}
    	else {
    		fetion_notification_show_post_result_message('verify_code_failed');
    	}
    	fetion_notification_show_settings_ui();
    }
    else {
    	fetion_notification_show_settings_ui();
    }
}

function fetion_notification_option_menu() {
    if (function_exists('add_options_page')) {
        add_options_page('飞信通知', '飞信通知', 9, basename(__FILE__), 'fetion_notification_show_settings');
    }
}

add_action('activate_fetion-notification/fetion-notification.php', 'fetion_notification_get_option');
add_action('admin_menu', 'fetion_notification_option_menu');

$options = fetion_notification_get_option();
if ($options['fetion_notification_notification_comment']) {
	add_filter('preprocess_comment', 'fetion_notification_new_comment_notify');
}
if ($options['fetion_notification_notification_regist']) {
	add_action('user_register', 'fetion_notification_new_user_notify');
}